cmake_minimum_required(VERSION 3.2)

PROJECT(lua53)

LIST(APPEND CMAKE_MODULE_PATH ${CMAKE_CURRENT_SOURCE_DIR}/cmake)
INCLUDE(cmake/ModuleImport.cmake)
INCLUDE(cmake/ModuleCompileOptions.cmake)
ModuleSetCompileOptions()

SET(LUA53_VERSION_MAJOR "5")
SET(LUA53_VERSION_MINOR "1")
SET(LUA53_VERSION_PATCH "5")
SET(LUA53_VERSION "${LUA53_VERSION_MAJOR}.${LUA53_VERSION_MINOR}.${LUA53_VERSION_PATCH}")

MESSAGE(STATUS "VERSION: ${LUA51_VERSION}")

ADD_DEFINITIONS(-DUSE_LUA51)
ADD_DEFINITIONS(-DLUA_COMPAT_MODULE -DLUA_COMPAT_APIINTCASTS)
OPTION(USE_LUA53_INNER "use lua inner" ON)

INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/)
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/include)
INCLUDE_DIRECTORIES(${CMAKE_CURRENT_SOURCE_DIR}/src)

FILE(GLOB DMLUA_SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/src/*.cpp
${CMAKE_CURRENT_SOURCE_DIR}/src/*.cc
${CMAKE_CURRENT_SOURCE_DIR}/src/*.c
${CMAKE_CURRENT_SOURCE_DIR}/src/*.hpp
${CMAKE_CURRENT_SOURCE_DIR}/src/*.h
)

LIST(FILTER DMLUA_SOURCES EXCLUDE REGEX "lua.c$")
LIST(FILTER DMLUA_SOURCES EXCLUDE REGEX "luac.c$")
LIST(FILTER DMLUA_SOURCES EXCLUDE REGEX "wmain.c$")

FILE(GLOB LUA_SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/src/lua.c
)

IF (WIN32)
    IF (USE_LUA53_INNER)
        ADD_LIBRARY(lua53 SHARED ${DMLUA_SOURCES})
        SET_TARGET_PROPERTIES(lua53 PROPERTIES COMPILE_FLAGS "-DLUA_BUILD_AS_DLL -DLUA_CORE")
        
        ADD_EXECUTABLE(lua ${LUA_SOURCES})
        TARGET_LINK_LIBRARIES(lua lua53)
    ENDIF(USE_LUA53_INNER)
ELSEIF (APPLE)
    ADD_DEFINITIONS(-DLUA_USE_MACOSX)

    IF (USE_LUA53_INNER)
        ADD_LIBRARY(lua53 SHARED ${DMLUA_SOURCES})
        SET_TARGET_PROPERTIES(lua53 PROPERTIES COMPILE_FLAGS "-Wl,-undefined -Wl,dynamic_lookup" )

        ADD_EXECUTABLE(lua ${LUA_SOURCES})
        TARGET_LINK_LIBRARIES(lua lua53 dl)
    ENDIF(USE_LUA53_INNER)
ELSEIF (UNIX)
    ADD_DEFINITIONS(-DLUA_USE_LINUX)

    IF (USE_LUA53_INNER)
        ADD_LIBRARY(lua53 SHARED ${DMLUA_SOURCES})
        SET_TARGET_PROPERTIES(lua53 PROPERTIES COMPILE_FLAGS "-Wl,-E" )

        ADD_EXECUTABLE(lua ${LUA_SOURCES})
        TARGET_LINK_LIBRARIES(lua lua53 m dl)
    ENDIF(USE_LUA53_INNER)
ENDIF ()

INSTALL(DIRECTORY include/
    DESTINATION include
    FILES_MATCHING PATTERN "*.h")

    
IF (WIN32)
    INSTALL(TARGETS lua lua53
        RUNTIME DESTINATION bin
        LIBRARY DESTINATION lib
        ARCHIVE DESTINATION lib)
ELSE(WIN32)
    INCLUDE(GNUInstallDirs)
    INSTALL(TARGETS lua lua53
    RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
    LIBRARY DESTINATION /${CMAKE_INSTALL_LIBDIR}
    ARCHIVE DESTINATION /${CMAKE_INSTALL_LIBDIR})
ENDIF(WIN32)

INCLUDE(cmake/cmake_uninstall.cmake)
ADD_UNINSTALL_TARGET()